const {getList, getDetail, newBlog, updateBlog, delBlog} = require('../controller/blog.js')
const {SuccessModel, ErrorModel} = require('../model/resModel.js')
//登陆验证的函数
const  loginCheck = (req)=>{
  if (!req.session.username){
    return Promise.resolve(
      new ErrorModel('尚未登陆')
    )
  }
}
const handleBlogRouter = (req, res) => {
  //获取方法
  const method = req.method
  //获取id
  const id = req.query.id
  
  //获取博客列表
  if (method === 'GET' && req.path === '/api/blog/list') {
    let author = req.query.author || ''
    let keyword = req.query.keyword || ''
    if (req.query.isadmin){
      const loginCheckResult = loginCheck(req)
      if (loginCheckResult){
        return loginCheckResult
      }
      req.body.author = req.session.realname
    }
    const result = getList(req.body.author, keyword) //返回promise
    return result.then(listdata => {
      return new SuccessModel(listdata)
    })
  }
  
  //获取博客详细
  if (method === 'GET' && req.path === '/api/blog/detail') {
    const result = getDetail(id)
    return result.then(data=>{
      return new SuccessModel(data)
    })
    
  }
  //新建博客
  if (method === 'POST' && req.path === '/api/blog/new') {
    const loginCheckResult = loginCheck(req)
    if (loginCheckResult){
      return loginCheckResult
    }
    req.body.author = req.session.realname
    const result = newBlog(req.body)
    return result.then(data=>{
      return new SuccessModel(data)
    })
  }
  
  //更新博客
  if (method === 'POST' && req.path === '/api/blog/update') {
    const loginCheckResult = loginCheck(req)
    if (loginCheckResult){
      return loginCheckResult
    }
    const result = updateBlog(id,req.body)
    return result.then(value => {
      if (value) {
        return new SuccessModel(result)
      } else {
        return new ErrorModel('更新博客失败')
      }
    })
  }
  
  //删除博客
  if (method === 'POST' && req.path === '/api/blog/del') {
    const loginCheckResult = loginCheck(req)
    if (loginCheckResult){
      return loginCheckResult
    }
    const result = delBlog(id,req.session.realname)
    return result.then(value => {
      if (value) {
        return new SuccessModel('删除成功')
      } else {
        return new ErrorModel('删除博客失败')
      }
    })
    
  }
}

module.exports = handleBlogRouter
